package org.huzhp.gateway.filter.balance.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.huzhp.gateway.filter.balance.WeightServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @Description: 权重
 * @Author: huzp
 * @CreateDate: 2020/4/17 16:10
 * @Version: 1.0
 */
public class WeightLoadBalancerRule extends AbstractLoadBalancerRule {

    private static final Logger logger  = LoggerFactory.getLogger(WeightLoadBalancerRule.class);

    private int sumWeight;

    //初始权重
    private int[] weights;
    //当前权重
    private int[] currents;


    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        System.out.println();
    }
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }
                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

                server = this.weightIndex(upList);

                if (logger.isInfoEnabled()){
                    logger.info("Weight choose server {}",server);
                }

                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }
            return server;
        }
    }

    private Server weightIndex(List<Server> servers){
        if (sumWeight==0 || weights == null) {
            int length = servers.size();
            weights = new int[length];
            currents = new int[length];
            for (int i = 0; i < length; i++) {
                WeightServer weightServer = (WeightServer) servers.get(i);
                sumWeight += weightServer.getWeight();
                weights[i] = weightServer.getWeight();
                currents[i] = weightServer.getWeight();
            }
        }
        return servers.get(getNext());
    }

    private synchronized int getNext(){
        int index = 0;
        int max = 0;
        int length = weights.length;
        for (int i=0;i<length;i++) {
            if (currents[i]>max){
                max = currents[i];
                index = i;
            }
        }
        currents[index] = currents[index] - sumWeight;
        for(int i=0;i<length;i++){
            currents[i] += weights[i];
        }
        return index;
    }

    @Override
    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }
}
